package com.cskaoyan.market.controller;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/wx/storage/fetch/*")
public class WxStorageFetchController extends HttpServlet {

    private String basePath="D:\\image";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String key = requestURI.replace(req.getContextPath() + "/wx/storage/fetch/", "");
        String filePath=basePath+"/"+key;
        File file = new File(filePath);
        if(file.exists()&&file.isFile()){
            ServletOutputStream outputStream = resp.getOutputStream();
            FileInputStream fileInputStream = new FileInputStream(file);
            int length;
            byte[] bytes = new byte[1024];
            while ((length=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,length);
            }
            return;
        }
        resp.setStatus(404);
    }
}
